<template>
    <el-dialog :title="title" v-model="open" width="71%" append-to-body style="margin-top: 9px!important;">
        <el-form ref="meetingInfoRef" :model="form" :rules="rules" label-width="109px">
            <el-row>
            <el-col :span="24">
                <el-form-item label="会议名称" prop="title">
                <el-input v-model="form.title" placeholder="请输入会议名称" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-row>
                <el-col :span="12">
                    <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker clearable
                        v-model="form.startTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择开始时间"
                        style="width: 100%;">
                    </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="会议时长" prop="durtion">
                    <el-input v-model="form.durtion" placeholder="会议时长">
                        <template #append>分钟</template>
                    </el-input>
                    </el-form-item>
                </el-col>
                </el-row>
            </el-col>
            <el-col :span="24">
                <el-form-item label="发布组织" prop="deptId" style="width: 100%;">
                <el-tree-select
                    v-model="form.deptId"
                    :data="deptOptions"
                    :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                    value-key="deptId"
                    placeholder="请选择发布组织"
                    check-strictly
                />
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item class="typeCodeStyle" label="会议类型" prop="typeCode">
                <el-radio-group v-model="form.typeCode">
                    <el-radio v-for="meetingType in pb_meeting_type" :key="meetingType.value" :label="meetingType.label" :value="meetingType.value"></el-radio>
                </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item class="typeCodeStyle" label="会议议题" prop="meetingTopic">
                <el-radio-group v-model="form.meetingTopic">
                    <el-radio v-for="meetTopic in pb_meeting_topic" :key="meetTopic.value" :label="meetTopic.label" :value="meetTopic.value"></el-radio>
                </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="会议形式" prop="meetingWay">
                <el-radio-group v-model="form.meetingWay">
                    <el-radio v-for="meetWay in sys_meeting_way" :key="meetWay.value" :label="meetWay.label" :value="meetWay.value"></el-radio>
                </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="具体形式" prop="detailWay">
                <el-input v-model="form.detailWay" placeholder="请输入具体形式" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="签到方式" prop="signWays">
                <el-checkbox-group v-model="signWays">
                    <el-checkbox v-for="sign in pb_sign_way" :key="sign.value" :label="sign.label" :value="sign.value"></el-checkbox>
                </el-checkbox-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="会议地点" prop="meetingAddr">
                  <el-input v-model="form.meetingAddr" placeholder="请输入会议地点" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="详细地址" prop="detailAddr">
                <el-input v-model="form.detailAddr" placeholder="请输入详细地址" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item class="typeCodeStyle" label="参会人员" prop="userIdList">
                <div class="personDiv">
                    <div v-for="(item, index) in userNameList" :key="index" class="singlePersonDiv">
                    <div class="closeDiv" @click="closePerson(index, 'joiner')"><el-icon color="#999"><CloseBold /></el-icon></div>
                    <div class="circleAndText">
                        {{ item ? item.substring(1,3) : '' }}
                    </div>
                    <div class="bottomText">
                        {{ item }}
                    </div>
                    </div>
                    <div class="singlePersonDiv" @click="handleClickPeople">
                      <div class="circleAndText" style="background-color:#fff!important;border: 1px solid #ccc;">
                          <el-icon size="25" style="margin-top: 9px;margin-left: 0px;"><Plus /></el-icon>
                      </div>
                      <div class="bottomText">添加人员</div>
                    </div>
                </div>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item class="typeCodeStyle" label="列席人员" prop="attendance">
                  <el-input v-model="form.attendance" placeholder="请输入列席人员" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="会议内容">
                  <editor v-model="form.content" :height="390"/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="会议附件" prop="fileUrl">
                <file-upload
                    v-model="form.fileUrl"
                    :multiple="true"
                    :limit="10"
                    :file-type="['doc', 'docx', 'pdf']"
                    :file-size="200">
                </file-upload>
                </el-form-item>
            </el-col>
            <el-col :span="24" prop="record" v-if="isEditMeetRecord">
                <el-form-item label="会议记录">
                  <editor v-model="form.record" :height="390"/>
                </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 参会人员对话框 -->
    <select-people ref="userPeopleRef" :parentMethod="userPeopleMethod"></select-people>
    <!-- 列席人员对话框
    <select-people ref="attendancePeopleRef" :parentMethod="attendancePeopleMethod"></select-people> -->
</template>
  
<script setup>
import { listAllMember } from "@/api/partybuilding/Member";
import { listOrg } from "@/api/partybuilding/Org";
import { getMeetingInfo, addMeetingInfo, updateMeetingInfo } from "@/api/partybuilding/MeetingInfo";
import SelectPeople from './SelectPeople.vue'
const props = defineProps({
  parentMethod: {
    type: Function,
    required: true,
    default: () => {}
  }
})
const { proxy } = getCurrentInstance();
const open = ref(false);
const deptOptions = ref(undefined);
const userPeopleRef = ref(null);
const attendancePeopleRef = ref(null);
const userList = ref([]);
const userIdList = ref([]);
const userNameList = ref([]);
// const attendanceIdList = ref([]);
// const attendanceNameList = ref([]);
const title = ref("");
const signInEnd = ref(null);
const qrcodeUrl = ref("");
const signWays = ref([]);
// const typeCodes = ref([]);
// const meetingTopics = ref([]);
const { pb_sign_way } = proxy.useDict("pb_sign_way");
const { pb_meeting_topic } = proxy.useDict("pb_meeting_topic");
const { pb_meeting_type } = proxy.useDict("pb_meeting_type");
const { sys_meeting_way } = proxy.useDict("sys_meeting_way");
const { sys_meeting_status } = proxy.useDict("sys_meeting_status");
const { pb_meeting_sign_delay } = proxy.useDict("pb_meeting_sign_delay");
const isEditMeetRecord = ref(false);

const data = reactive({
    form: {
        id: null,
        typeName: null,
        status: null,
        title: null,
        startTime: null,
        durtion: null,
        deptId: null,
        deptName: null,
        typeCode: null,
        meetingTopic: null,
        meetingWay: null,
        detailWay: null,
        signWay: null,
        meetingAddr: null,
        detailAddr: null,
        users: null,
        attendance: null,
        content: null,
        fileUrl: null,
        createrId: null,
        createTime: null
    },
    queryPeopleParams: {
      pageNum: 1,
      pageSize: 900,
      deptId: null,
    },
    rules: {
      title: [
        { required: true, message: "会议名称不能为空", trigger: "blur" }
      ],
      startTime: [
        { required: true, message: "开始时间不能为空", trigger: "blur" }
      ],
      durtion: [
        { required: true, message: "会议时长不能为空", trigger: "blur" }
      ],
      deptId: [
        { required: true, message: "发布组织不能为空", trigger: "blur" }
      ],
      typeCode: [
        { required: true, message: "请选择会议类型", trigger: "blur" }
      ],
      meetingTopic: [
        { required: true, message: "请选择会议议题", trigger: "blur" }
      ],
      // typeCodes: [
      //   { validator: (rule, value, callback) => {
      //       if (typeCodes.value==null || typeCodes.value=="") {
      //         callback(new Error("请选择会议类型")); 
      //       } else {
      //         callback(); 
      //       }
      //     }, 
      //     trigger: ["change", "blur"] 
      //   }
      // ],
      // meetingTopics: [
      //   { validator: (rule, value, callback) => {
      //       if (meetingTopics.value==null || meetingTopics.value=="") {
      //         callback(new Error("请选择会议议题")); 
      //       } else {
      //         callback(); 
      //       }
      //     }, 
      //     trigger: ["change", "blur"] 
      //   }
      // ],
      userIdList: [
        { validator: (rule, value, callback) => {
            if (userNameList.value==null || userNameList.value=="") {
              callback(new Error("请选择参会人员")); 
            } else {
              callback(); 
            }
          }, 
          trigger: ["change", "blur"] 
        }
      ]
    }
});
  
const { form, queryPeopleParams, rules } = toRefs(data);

const show = (id, isEditRecord) => {
    isEditMeetRecord.value = isEditRecord;
    if (id!= null) {
        handleUpdate(id);
    } else {
        handleAdd();
    }
    open.value = true;
};

defineExpose({
    show
});

/** 新增按钮操作 */
function handleAdd() {
    reset();
    form.value.meetingWay = '0';
    form.value.content = '<p></p>';
    signWays.value = [];
    signWays.value.push('0');
    open.value = true;
    title.value = "添加会议信息";
}
  
/** 修改按钮操作 */
function handleUpdate(id) {
    reset();
    getMeetingInfo(id).then(response => {
      form.value = response.data;
      getDetailVo();
      open.value = true;
      title.value = "修改会议信息";
    });
}

/** 查询部门下拉树结构 */
function getDeptTree() {
    listOrg().then(response => {
        deptOptions.value = proxy.handleTree(response.rows, "deptId");
    });
};
/** 查询用户列表 */
function getPeopleList() {
    listAllMember(queryPeopleParams.value).then(res => {
      userList.value = res.data;
    });
};

onMounted(() => {
    getDeptTree();
    getPeopleList();
})

// 关闭参会人和列席人弹窗
function closePerson(index, type){
    if (type == 'joiner') {
        userIdList.value.splice(index, 1);
        userNameList.value.splice(index, 1);
    } else {
        // attendanceIdList.value.splice(index, 1);
        // attendanceNameList.value.splice(index, 1);
    }
}

//单击参会人
function handleClickPeople() {
    userPeopleRef.value.show();
}

//参会人回调函数
function userPeopleMethod(uIdList, uNameList) {
    if (uIdList!=null && uIdList.length>0) {
        uIdList.forEach((item, index) => {
        if (!userIdList.value.includes(item)) {
            userIdList.value.push(item);
            userNameList.value.push(uNameList[index]);
        }
        });
    }
}

//单击列席人
// function handleClickAttendance() {
//     attendancePeopleRef.value.show();
// }

//列席人回调函数
// function attendancePeopleMethod(uIdList, uNameList) {
//   if (uIdList!=null && uIdList.length>0) {
//       uIdList.forEach((item, index) => {
//       if (!attendanceIdList.value.includes(item)) {
//           attendanceIdList.value.push(item);
//           attendanceNameList.value.push(uNameList[index]);
//       }
//       });
//   }
// }


function getDetailVo() {
    userIdList.value = [];
    // typeCodes.value = [];
    // meetingTopics.value = [];
    // if (form.value.typeCode) {
    //   typeCodes.value = form.value.typeCode.split(",");
    // }
    // if (form.value.meetingTopic) {
    //   meetingTopics.value = form.value.meetingTopic.split(",");
    // }
    signWays.value = [];
    if (form.value.signWay!=null) {
      signWays.value.push(form.value.signWay+'');
    }
    form.value.meetingWay = form.value.meetingWay+'';
    form.value.content = form.value.content? form.value.content : '<p></p>';
    form.value.record = form.value.record? form.value.record : '<p></p>';
    //参会人员
    if (form.value.users && form.value.users.length > 0) {
      let arrId = [];
      let arrName = [];
      JSON.parse(form.value.users).forEach(item => {
        arrId.push(item);
        let user = userList.value.find(user => user.userId == item);
        if (user) {
          arrName.push(user.nickName);
        } else {
          arrName.push("");
        }
      });
      userIdList.value = arrId;
      userNameList.value = arrName;
    }
    //列席人员
    // if (form.value.attendance && form.value.attendance.length > 0) {
    //   let arrId = [];
    //   let arrName = [];
    //   JSON.parse(form.value.attendance).forEach(item => {
    //     arrId.push(item);
    //     let user = userList.value.find(user => user.userId == item);
    //     if (user) {
    //       arrName.push(user.nickName);
    //     } else {
    //       arrName.push("");
    //     }
    //   });
    //   attendanceIdList.value = arrId;
    //   attendanceNameList.value = arrName;
    // }
    //附件
    if (form.value.fileUrl!=null && form.value.fileUrl.length > 0){
      let arr = [];
      JSON.parse(form.value.fileUrl).forEach(item => {
        arr.push(item);
      });
      form.value.fileUrl = arr.join(",");
    }
}
  
function getJsonArrString(fileUrl){
    let arr = [];
    fileUrl.split(",").forEach(item => {
        arr.push(item);
    });
    return JSON.stringify(arr);
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["meetingInfoRef"].validate(valid => {
        if (valid) {
            form.value.users = getJsonArrString(userIdList.value.join(","));
            // form.value.attendance = getJsonArrString(attendanceIdList.value.join(","));
            // form.value.typeCode = typeCodes.value.join(",");
            // form.value.meetingTopic = meetingTopics.value.join(",");
            form.value.signWay = signWays.value.length > 0 ? signWays.value[0] : null;
            //附件
            if (form.value.fileUrl!=null && form.value.fileUrl.length > 0){
                form.value.fileUrl = getJsonArrString(form.value.fileUrl);
            }
            if (form.value.id != null) {
                updateMeetingInfo(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    props.parentMethod();
                    open.value = false;
                });
            } else {
                addMeetingInfo(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    props.parentMethod();
                    open.value = false;
                });
            }
        }
    });
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        typeName: null,
        status: null,
        title: null,
        startTime: null,
        durtion: null,
        deptId: null,
        deptName: null,
        typeCode: null,
        meetingTopic: null,
        meetingWay: null,
        detailWay: null,
        signWay: null,
        meetingAddr: null,
        detailAddr: null,
        users: null,
        attendance: null,
        content: null,
        fileUrl: null,
        createrId: null,
        createTime: null
    };
    proxy.resetForm("meetingInfoRef");
    // typeCodes.value = []; //会议类型
    // meetingTopics.value = []; //会议议题
    userIdList.value = []; //参会人员
    userNameList.value = []; //参会人员名称
    // attendanceIdList.value = []; //列席人员
    // attendanceNameList.value = []; //列席人员名称
    signWays.value = []; //签到方式
}


// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
</script>
<style lang="scss" scoped>
.typeCodeStyle {
    position: relative;
}
.typeCodeStyle::before {
  content: "*";
  color: #F56C6C;
  position: absolute;
  left: 31px;
  top: 9px;
}
.personDiv {
  margin: 5px;
}
.singlePersonDiv {
  position: relative;
  display: block;
  width: 64px;
  height: 66px;
  float: left;
  margin-top: 10px;
  margin-bottom: 15px;
  margin-right: 10px;
  cursor: pointer;
  .closeDiv {
      position: absolute;
      top: -11px;
      right: 7px;
      font-size: 16px;
      cursor: pointer;
  }
  .circleAndText {
      width: 44px;
      height: 44px;
      line-height: 44px;
      text-align: center;
      border-radius: 50%;
      border: 1px solid #ffe3e3;
      color: #333;
      font-size: 14px;
      background-color: rgba(255, 77, 79, .06);
  }
  .bottomText {
      font-size: 14px;
      color: #595959;
      margin-top: -1px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
  }
}
</style>